package hotciv.variant;

import hotciv.framework.*;
import hotciv.standard.*;

public class AlphaCivMoveUnitStrategy implements MoveUnitStrategy {

	public boolean moveUnit(GameTesting g, Position from, Position to) {
		
		/** check preconditions */
		g.isWithinWorldLimit(from);
		g.isWithinWorldLimit(to);
		Tile destination = g.getTile(to);
		Unit unitAtDest = g.getUnitAt(to);
		Unit unitToMove = g.getUnitAt(from);
		if(unitToMove == null) return false;//throw new MoveErrorException("No unit at "+from+"!");
		if(destination.getTypeString() == GameConstants.MOUNTAINS)
			return false;//throw new MoveErrorException("Cannot move over mountains!");
		if(destination.getTypeString() == GameConstants.OCEANS)
			return false;//throw new MoveErrorException("Cannot move thrugh water!");
		if(unitToMove.getOwner() != g.getPlayerInTurn()) 
			return false;//throw new MoveErrorException("Cannot move "+unitToMove.getOwner().getColor()+"'s units");
		if(unitToMove.getMoveCount() < 1) return false; //throw new MoveErrorException("No moves left!");
		if(from.equals(to)) return false;//move to same location
		if(unitAtDest != null && unitAtDest == g.getPlayerInTurn())
			return false; //players unit already at tile
		
		/** move the unit here */
		System.out.println(unitToMove.getMoveCount());
		unitToMove.decrementMoveCount();
		g.getTile(from).removeTopUnit();
		if(Math.abs(from.getColumn()-to.getColumn()) > 1) return false;
		System.out.println(unitToMove.getMoveCount());
		//if enemy unit there
		//System.out.println(inTurn.getColor()+" found... removing:"+unitAtDest.getOwner());
		if(unitAtDest != null && unitAtDest.getOwner() != g.getPlayerInTurn()) {
			//System.out.println(to+" - "+inTurn+" found enemy UNIT... killing "+unitAtDest.getOwner()+" "+unitAtDest.getTypeString());
			destination.removeTopUnit();
		}
		destination.addUnit(unitToMove);

		//if enemy city there
		CityTesting cityInTheWay = (CityTesting)g.getCityAt(to);
		if(cityInTheWay != null && cityInTheWay.getOwner() != g.getPlayerInTurn()) {
			//int residents = cityInTheWay.getSize();
			//System.out.println(to+" - "+inTurn+" found enemy CITY... takeing over "+cityInTheWay.getOwner()+" city");
			//destination.getCityList().remove(cityInTheWay);
			//destination.addCity(new StandardCity(inTurn,residents));
			cityInTheWay.setOwner(g.getPlayerInTurn());
			
		}
		//if(this.getWinner() != null)
		//	System.out.println(this.getWinner()+" is the winner!");

		return true;
	}
	}